package com.zzhrtech.wgzx_cityzen.ui.me;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.GsonRequest;
import com.bumptech.glide.Glide;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.zzhrtech.WgzxApplication;
import com.zzhrtech.wgzx_cityzen.BaseActivity;
import com.zzhrtech.wgzx_cityzen.Constans;
import com.zzhrtech.wgzx_cityzen.R;
import com.zzhrtech.wgzx_cityzen.beans.contact.PrizeListBean;
import com.zzhrtech.wgzx_cityzen.beans.me.CodeBean;
import com.zzhrtech.wgzx_cityzen.beans.task.BaseBean;
import com.zzhrtech.wgzx_cityzen.utils.CountDownButtonHelper;
import com.zzhrtech.wgzx_cityzen.utils.OkHttpPicManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.hdodenhof.circleimageview.CircleImageView;
import me.iwf.photopicker.PhotoPicker;

public class RegisterActivity extends BaseActivity {

    private EditText mEmailView,mNickView,msmscode,mAccount;
    private EditText mPasswordView;
    private TextView tv_login,tv_head,text_yhxy;
    private CircleImageView civ_head;
    private Button btn_reg,btn_sms;
    private CheckBox check_yhxy;
    private CountDownButtonHelper buttonHelper;
    private int truesmsCode;
    private String email,nickname,password,smscode,account;
    ArrayList<String> photos = new ArrayList<String>();
    private final OkHttpClient client = new OkHttpClient();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        toolbar.setNavigationIcon(R.mipmap.ic_close);

        civ_head = (CircleImageView) findViewById(R.id.civ_head);
        mEmailView = (EditText) findViewById(R.id.email);
        mNickView = (EditText) findViewById(R.id.nickname);
        mPasswordView = (EditText) findViewById(R.id.password);
        msmscode = (EditText) findViewById(R.id.smscode);
        btn_reg = (Button) findViewById(R.id.btn_reg);
        btn_sms = (Button) findViewById(R.id.btn_sms);
        tv_login = (TextView) findViewById(R.id.tv_login);
        tv_head = (TextView) findViewById(R.id.tv_head);
        text_yhxy = (TextView) findViewById(R.id.text_yhxy);
        check_yhxy = (CheckBox) findViewById(R.id.check_yhxy);
        mAccount = (EditText) findViewById(R.id.account);

        text_yhxy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RegisterActivity.this,WebviewActivity.class);
                intent.putExtra("url",HTTP_YHXT);
                intent.putExtra("title","用户协议");
                startActivity(intent);
            }
        });

        buttonHelper = new CountDownButtonHelper(btn_sms,"获取验证码",60,1);

        btn_sms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                email = mEmailView.getText().toString();

                if (TextUtils.isEmpty(email) || !isPhoneNumberValid(email)) {
                    mEmailView.setError("电话号码有误");
                }else {
                    httpGetCode();
                }
            }
        });

        civ_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                checkPermission();

            }
        });

        tv_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btn_reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                attemptRegister();
            }
        });
    }

    private void attemptRegister(){
        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);
        mNickView.setError(null);
        msmscode.setError(null);
        mAccount.setError(null);

        // Store values at the time of the login attempt.
        email = mEmailView.getText().toString();
        nickname = mNickView.getText().toString();
        password = mPasswordView.getText().toString();
        smscode = msmscode.getText().toString();
        account = mAccount.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (TextUtils.isEmpty(password) || !isPasswordValid(password)) {
            mPasswordView.setError("密码太短");
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email) || !isPhoneNumberValid(email)) {
            mEmailView.setError("电话号码有误");
            focusView = mEmailView;
            cancel = true;
        }

        if (TextUtils.isEmpty(account)) {
            mAccount.setError("请输入帐号! ");
            focusView = mAccount;
            cancel = true;
        }

        if (TextUtils.isEmpty(nickname)) {
            mNickView.setError("请输入昵称! ");
            focusView = mNickView;
            cancel = true;
        }

        if (TextUtils.isEmpty(smscode)){
            msmscode.setError("请输入验证码！");
            focusView = msmscode;
            cancel = true;
        }

        if (!smscode.equals(String.valueOf(truesmsCode))){
            msmscode.setError("验证码错误！");
            focusView = msmscode;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.

            if (photos.size() == 0){
                showToast("请选择头像！");
            }else {
                httpRegister();
            }
        }
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    private void checkPermission() {

        int readStoragePermissionState = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        int cameraPermissionState = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);

        boolean readStoragePermissionGranted = readStoragePermissionState != PackageManager.PERMISSION_GRANTED;
        boolean cameraPermissionGranted = cameraPermissionState != PackageManager.PERMISSION_GRANTED;

        if (readStoragePermissionGranted || cameraPermissionGranted) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
                    || ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {

                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {
                String[] permissions;
                if (readStoragePermissionGranted && cameraPermissionGranted) {
                    permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA };
                } else {
                    permissions = new String[] {
                            readStoragePermissionGranted ? Manifest.permission.READ_EXTERNAL_STORAGE
                                    : Manifest.permission.CAMERA
                    };
                }
                ActivityCompat.requestPermissions(this,
                        permissions,
                        123);
            }

        } else {
            // Permission granted

            PhotoPicker.builder()
                    .setPhotoCount(1)
                    .setShowCamera(true)
                    .setShowGif(true)
                    .setPreviewEnabled(false)
                    .start(RegisterActivity.this, PhotoPicker.REQUEST_CODE);

        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            PhotoPicker.builder()
                    .setPhotoCount(1)
                    .setShowCamera(true)
                    .setShowGif(true)
                    .setPreviewEnabled(false)
                    .start(RegisterActivity.this, PhotoPicker.REQUEST_CODE);
        }else {

        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                 photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);


                Glide.with(RegisterActivity.this)
                        .load(photos.get(0))
                        .into(civ_head);

                tv_head.setText("已上传");
            }
        }
    }


    private void httpGetCode(){
        Map<String,String> map = new HashMap<String, String>();
        map.put("phone",email);
        map.put("type","1");

        GsonRequest<CodeBean> gsonRequest = new GsonRequest<CodeBean>(com.android.volley.Request.Method.POST, Constans.HTTP_GETCODE, CodeBean.class, map, new com.android.volley.Response.Listener<CodeBean>() {
            @Override
            public void onResponse(CodeBean response) {

                if (response.isSuccess()) {
                    showToast("获取成功");

                    truesmsCode = response.getData();
                    buttonHelper.start();
                }else {
                    showToast(response.getMsg());
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Log.d("result=====",error + "");
//                dialog.dismiss();
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }

    private void httpRegister(){

        Map<String, String> map = new HashMap<String, String>();
        map.put("username",email);
        map.put("nickname",nickname);
        map.put("account",account);
        map.put("password",password);

        Map<String, String> file = new HashMap<String, String>();
        if (photos.size() > 0)
        file.put("myFile",photos.get(0));

        //构建请求
        final Request request = new Request.Builder()
                .url(HTTP_REGISTER)//地址
                .post(new OkHttpPicManager().getBody(map, file))//添加请求体
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

                showToast("注册失败");

            }

            @Override
            public void onResponse(Response response) {

                try {
                    JSONObject object = new JSONObject(response.body().string());

                    if (object.getString("code").equals("0")) {

                        Looper.prepare();
                        showToast("注册成功");
                        setResult(RESULT_OK);
                        finish();
                        Looper.loop();


                    }else {
                        Looper.prepare();
                        showToast(object.getString("msg"));
                        Looper.loop();
                    }
                } catch (IOException e) {

                    e.printStackTrace();
                    Looper.prepare();
                    showToast("注册失败");
                    Looper.loop();
                } catch (JSONException e) {
                    showToast("注册失败");
                    Looper.prepare();
                    e.printStackTrace();
                    Looper.loop();
                }
            }
        });
    }


    /*检查字符串是否为电话号码的方法,并返回true or false的判断值*/
    public static boolean isPhoneNumberValid(String phoneNumber)
    {
        boolean isValid = false;
    /* 可接受的电话格式有:
     * ^\\(? : 可以使用 "(" 作为开头
     * (\\d{3}): 紧接着三个数字
     * \\)? : 可以使用")"接续
     * [- ]? : 在上述格式后可以使用具选择性的 "-".
     * (\\d{4}) : 再紧接着三个数字
     * [- ]? : 可以使用具选择性的 "-" 接续.
     * (\\d{4})$: 以四个数字结束.
     * 可以比较下列数字格式:
     * (123)456-78900, 123-4560-7890, 12345678900, (123)-4560-7890
    */
        String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{5})$";
        String expression2 ="^\\(?(\\d{3})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$";
        CharSequence inputStr = phoneNumber;
    /*创建Pattern*/
        Pattern pattern = Pattern.compile(expression);
    /*将Pattern 以参数传入Matcher作Regular expression*/
        Matcher matcher = pattern.matcher(inputStr);
    /*创建Pattern2*/
        Pattern pattern2 =Pattern.compile(expression2);
    /*将Pattern2 以参数传入Matcher2作Regular expression*/
        Matcher matcher2= pattern2.matcher(inputStr);
        if(matcher.matches()||matcher2.matches())
        {
            isValid = true;
        }
        return isValid;
    }
}
